﻿Option Infer On
Option Explicit On
Option Strict On

Imports System
Imports GenDotNet.Model.Common
Imports GenDotNet.Task.Common
Imports GenDotNet.TemplateSupport

Public Class GeneratorLinq
   Inherits GenerationBase

   Protected Overrides Function GetOutput( _
       ByVal name As String, _
       ByVal rootData As IRootData, _
       ByVal assemblyFileName As String, _
       ByVal templateName As String, _
       ByRef fileName As String) _
       As String
      Dim template = GetTemplate(assemblyFileName, templateName)
      If template IsNot Nothing Then
         Return template.Generate(name, rootData, fileName)
      End If
      Return Nothing
   End Function

   Private Function GetTemplate( _
            ByVal assemblyFileName As String, _
            ByVal templateName As String) _
            As ITemplate
      Dim asm As Reflection.Assembly = Nothing
      If Not String.IsNullOrEmpty(assemblyFileName) Then
         asm = Reflection.Assembly.LoadFrom(assemblyFileName)
         Dim type As Type = Nothing
         If asm IsNot Nothing And Not String.IsNullOrEmpty(templateName) Then
            type = GetSpecifiedType(asm, templateName)
            If type IsNot Nothing Then
               Dim obj = Activator.CreateInstance(type)
               Return TryCast(obj, ITemplate)
            End If
         End If
      End If
      Return Nothing
   End Function

   Private Shared Function GetSpecifiedType( _
            ByVal asm As Reflection.Assembly, _
            ByVal name As String) _
            As System.Type
      Dim type As System.Type = Nothing
      ' This is tempoary to test a fix

      Try
         Dim types = asm.GetTypes()
      Catch ex As Exception
         Console.WriteLine(ex)
      End Try

      ' Kind of ugly but it works
      For Each testType As System.Type In asm.GetTypes
         If testType.Name.EqualsIgnoreCase(name) Then
            type = testType
            Exit For
         End If
      Next
      Return type
   End Function


End Class
